LoginSignup
0
1

More than 1 year has passed since last update.

#WebAssembly #WASM の開発環境作成(サンプル動作含む。 #AssemblyScript ( #TypeScript 風)版。)

Last updated at Posted at 2022-05-12

本内容を利用した場合の一切の責任を私は負いません。

公式( https://www.assemblyscript.org/getting-started.html#setting-up-a-new-project )にガイドがあるが、自分がアホなのかうまくいかなかった。
開拓したらできたので載せておきます。

バージョン

  • OS
    OS 名: Microsoft Windows 10 Home
    OS バージョン: 10.0.19043 N/A ビルド 19043
    システムの種類: x64-based PC
  • node.js
    node-v16.15.0-win-x64.zip
  • AssemblyScript
    v0.20.6
  • Chrome
    バージョン: 101.0.4951.54(Official Build) (64 ビット)

準備

node.jsをダウンロード・展開し、PATH(node.exeの場所を追加)とNODE_PATH(node.exeの場所の下のnode_modulesのパス)の環境変数を設定する。
AssemblyScriptのリリースを公式( https://github.com/AssemblyScript/assemblyscript/releases/tag/v0.20.6 )からダウンロード・展開する。
(公式ではオンラインでインストールしているが、これだとnpmが死んだり、最新のAssemblyScriptがインストールされたりしてうまく動かないっぽい。
コミット履歴を見るとリリース以降にコミットがあるため、npmでインストールするとその分も反映されてしまうからかも。)

手順

  1. 作業フォルダ作成
  2. 作業フォルダに展開したAssemblyScriptのフォルダを移動
    移動したAssemblyScriptの直下にAssemblyScriptのpackage.jsonがあるように階層を調整する。
  3. AssemblyScriptインストール
    カレントにAssemblyScriptフォルダがある状態で下記を実行する。
    npm install assemblyscript
    (下記でバージョンが正しいか確認する。
    npm list)
  4. npm link
    公式にはないが、公式のgithub( https://github.com/AssemblyScript/assemblyscript )には書いてあるため実行する。
    下記のエラーが出るが詳細不明。
実行結果
npm ERR! Cannot read properties of undefined (reading 'name')

npm ERR! A complete log of this run can be found in:
npm ERR!     ~debug-0.log
~debug-0.log
~
40 verbose stack TypeError: Cannot read properties of undefined (reading 'name')
40 verbose stack     at ~\node-v16.15.0-win-x64\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\reify.js:285:30
  1. npx asinit .(Markdownのバグで実際は手順5)
    公式にある通り。
    最後の問いでYにすると、公式の通りフォルダ等一式が作られる。

  2. npm run asbuild
    公式にある通り。

出力
> asbuild
> npm run asbuild:debug && npm run asbuild:release


> asbuild:debug
> asc assembly/index.ts --target debug


> asbuild:release
> asc assembly/index.ts --target release
  1. npm test(Markdownのバグで実際は手順7)
    公式にある通り。
出力
> test
> node tests

ok

  1. npm start(Markdownのバグで実際は手順8)
    公式にある通り。
出力
Need to install the following packages:
  serve
Ok to proceed? (y) y

   ┌──────────────────────────────────────────────────┐
   │                                                  │
   │   Serving!                                       │
   │                                                  │
   │   - Local:            http://localhost:3000      │
   │   - On Your Network:  http://192.168.11.2:3000   │
   │                                                  │
   │   Copied local address to clipboard!             │
   │                                                  │
   └──────────────────────────────────────────────────┘

1.ブラウザからアクセス(Markdownのバグで実際は手順9)
前手順の出力にある http://localhost:3000 を開くと下記になっている。
WebAssembly.PNG
Webページのソースを見ると、1+2の指示を出しているが、3を表示する処理はなく、WebAssemblyが処理していることがわかる。

備考

[ライフゲームのサンプル]
公式のgithubにある「Examples」のリンクを押すとサンプルページ(P1)に行きます。
「Examples repository」の中の「examples repository」のリンクを押すとリポジトリに行きます。
リポジトリをZIPでダウンロード・展開します。
「game-of-life」フォルダ下でnpm startを実行します。
表示されるURLをブラウザから開きます。

[五目並べのサンプル]
P1の中の「Built with AssemblyScript」のリンクを押すと他のサンプルのページに行きます。
「Gomoku WASM」の右の「play」を押すと遊べます。
gomoku.PNG

[asc(tsc?)の違い]
AssemblyScriptがリアルタイムで更新されているためか、失敗した時は別物のようだった。
失敗した時と成功した時のnpx asc -hの出力は下記。
自分がやった時はtargetオプションの引数が違うために進まなかった。

成功時出力
D:\TMP\wasm3>npx asc -h
SYNTAX
  asc [entryFile ...] [options]

EXAMPLES
  asc hello.ts
  asc hello.ts -o hello.wasm -t hello.wat
  asc hello1.ts hello2.ts -o -O > hello.wasm
  asc --config asconfig.json --target release

OPTIONS

 General

  --version, -v         Prints just the compiler's version and exits.
  --help, -h            Prints this message and exits.
  --config              Configuration file to apply. CLI arguments take precedence.
  --target              Configuration file target to use. Defaults to 'release'.

 Optimization

  --optimize, -O        Optimizes the module. Typical shorthands are:

                         Default optimizations   -O
                         Make a release build    -O --noAssert
                         Make a debug build      --debug
                         Optimize for speed      -Ospeed
                         Optimize for size       -Osize

  --optimizeLevel       How much to focus on optimizing code. [0-3]
  --shrinkLevel         How much to focus on shrinking code size. [0-2, s=1, z=2]
  --converge            Re-optimizes until no further improvements can be made.
  --noAssert            Replaces assertions with just their value without trapping.

 Output

  --outFile, -o         Specifies the WebAssembly output file (.wasm).
  --textFile, -t        Specifies the WebAssembly text output file (.wat).
  --bindings, -b        Specifies the bindings to generate (.js + .d.ts).

                          esm  JavaScript bindings & typings for ESM integration.
                          raw  Like esm, but exports just the instantiate function.
                               Useful where modules are meant to be instantiated
                               multiple times or non-ESM imports must be provided.

 Debugging

  --sourceMap           Enables source map generation. Optionally takes the URL
                        used to reference the source map from the binary file.
  --debug               Enables debug information in emitted binaries.

 Features

  --importMemory        Imports the memory from 'env.memory'.
  --noExportMemory      Does not export the memory as 'memory'.
  --initialMemory       Sets the initial memory size in pages.
  --maximumMemory       Sets the maximum memory size in pages.
  --sharedMemory        Declare memory as shared. Requires maximumMemory.
  --zeroFilledMemory    Assume imported memory is zeroed. Requires importMemory.
  --importTable         Imports the function table from 'env.table'.
  --exportTable         Exports the function table as 'table'.
  --exportStart         Exports the start function using the specified name instead
                        of calling it implicitly. Useful for WASI or to obtain the
                        exported memory before executing any code accessing it.
  --runtime             Specifies the runtime variant to include in the program.

                         incremental  TLSF + incremental GC (default)
                         minimal      TLSF + lightweight GC invoked externally
                         stub         Minimal runtime stub (never frees)
                         ...          Path to a custom runtime implementation

  --exportRuntime       Exports the runtime helpers (__new, __collect etc.).
  --stackSize           Overrides the stack size. Only relevant for incremental GC
                        or when using a custom runtime that requires stack space.
                        Defaults to 0 without and to 16384 with incremental GC.
  --enable              Enables WebAssembly features being disabled by default.

                         threads             Threading and atomic operations.
                         simd                SIMD types and operations.
                         reference-types     Reference types and operations.
                         gc                  Garbage collection (WIP).

  --disable             Disables WebAssembly features being enabled by default.

                         mutable-globals     Mutable global imports and exports.
                         sign-extension      Sign-extension operations
                         nontrapping-f2i     Non-trapping float to integer ops.
                         bulk-memory         Bulk memory operations.

  --use, -u             Aliases a global object under another name, e.g., to switch
                        the default 'Math' implementation used: --use Math=JSMath
                        Can also be used to introduce an integer constant.
  --lowMemoryLimit      Enforces very low (<64k) memory constraints.

 Linking

  --memoryBase          Sets the start offset of emitted memory segments.
  --tableBase           Sets the start offset of emitted table elements.

 API

  --transform           Specifies the path to a custom transform to load.

 Binaryen

  --trapMode            Sets the trap mode to use.

                         allow  Allow trapping operations. This is the default.
                         clamp  Replace trapping operations with clamping semantics.
                         js     Replace trapping operations with JS semantics.

  --runPasses           Specifies additional Binaryen passes to run after other
                        optimizations, if any. See: Binaryen/src/passes/pass.cpp
  --noValidate          Skips validating the module using Binaryen.

 Other

  --baseDir             Specifies the base directory of input and output files.
  --noColors            Disables terminal colors.
  --noUnsafe            Disallows the use of unsafe features in user code.
                        Does not affect library files and external modules.
  --noEmit              Performs compilation as usual but does not emit code.
  --showConfig          Print computed compiler options and exit.
  --stats               Prints statistics on I/O and compile times.
  --pedantic            Make yourself sad for no good reason.
  --lib                 Adds one or multiple paths to custom library components and
                        uses exports of all top-level files at this path as globals.
  --path                Adds one or multiple paths to package resolution, similar
                        to node_modules. Prefers an 'ascMain' entry in a package's
                        package.json and falls back to an inner 'assembly/' folder.
  --wasm                Uses the specified Wasm binary of the compiler.
  -- ...                Specifies node.js options (CLI only). See: node --help

D:\TMP\wasm3>
失敗時出力
D:\TMP\wasm>npx asc -h
Version 2.9.2
Syntax:   tsc [options] [file ...]

Examples: tsc hello.ts
          tsc --outFile file.js file.ts
          tsc @args.txt

Options:
 -h, --help                                         Print this message.
 --all                                              Show all compiler options.
 -v, --version                                      Print the compiler's version.
 --init                                             Initializes a TypeScript project and creates a tsconfig.json file.
 -p FILE OR DIRECTORY, --project FILE OR DIRECTORY  Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.
 --pretty                                           Stylize errors and messages using color and context (experimental).
 -w, --watch                                        Watch input files.
 -t VERSION, --target VERSION                       Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'.
 -m KIND, --module KIND                             Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'.
 --lib                                              Specify library files to be included in the compilation.
                                                      'es5' 'es6' 'es2015' 'es7' 'es2016' 'es2017' 'es2018' 'esnext' 'dom' 'dom.iterable' 'webworker' 'scripthost' 'es2015.core' 'es2015.collection' 'es2015.generator' 'es2015.iterable' 'es2015.promise' 'es2015.proxy' 'es2015.reflect' 'es2015.symbol' 'es2015.symbol.wellknown' 'es2016.array.include' 'es2017.object' 'es2017.sharedmemory' 'es2017.string' 'es2017.intl' 'es2017.typedarrays' 'es2018.intl' 'es2018.promise' 'es2018.regexp' 'esnext.array' 'esnext.asynciterable'
 --allowJs                                          Allow javascript files to be compiled.
 --jsx KIND                                         Specify JSX code generation: 'preserve', 'react-native', or 'react'.
 -d, --declaration                                  Generates corresponding '.d.ts' file.
 --declarationMap                                   Generates a sourcemap for each corresponding '.d.ts' file.
 --sourceMap                                        Generates corresponding '.map' file.
 --outFile FILE                                     Concatenate and emit output to single file.
 --outDir DIRECTORY                                 Redirect output structure to the directory.
 --removeComments                                   Do not emit comments to output.
 --noEmit                                           Do not emit outputs.
 --strict                                           Enable all strict type-checking options.
 --noImplicitAny                                    Raise error on expressions and declarations with an implied 'any' type.
 --strictNullChecks                                 Enable strict null checks.
 --strictFunctionTypes                              Enable strict checking of function types.
 --strictPropertyInitialization                     Enable strict checking of property initialization in classes.
 --noImplicitThis                                   Raise error on 'this' expressions with an implied 'any' type.
 --alwaysStrict                                     Parse in strict mode and emit "use strict" for each source file.
 --noUnusedLocals                                   Report errors on unused locals.
 --noUnusedParameters                               Report errors on unused parameters.
 --noImplicitReturns                                Report error when not all code paths in function return a value.
 --noFallthroughCasesInSwitch                       Report errors for fallthrough cases in switch statement.
 --types                                            Type declaration files to be included in compilation.
 --esModuleInterop                                  Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.
 @<file>                                            Insert command line options and files from a file.

D:\TMP\wasm>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1